// axios 基础封装
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import router from '@/router'

//设置基础URL和超时时间
const httpInstance=axios.create({
    baseURL: 'http://pcapi-xiaotuxian-front-devtest.itheima.net',
  timeout: 5000
})


// axios请求拦截器
httpInstance.interceptors.request.use(config => {
  //1.从pinia获取token数据
  const userStore = useUserStore()
  const token = userStore.userInfo.token
  //2.如果存在token，添加到请求头中
  if (token) {
    config.headers.Authorization = `Bearer ${token}`
  }


    return config
  }, e => Promise.reject(e))
  
  // axios响应式拦截器
  httpInstance.interceptors.response.use(res => res.data, e => {
    //统一错误提示
    ElMessage.error(e.response.data.message)
    //401token过期，清除用户信息
    if (e.response.status === 401) {
      const userStore = useUserStore()
      userStore.clearUserInfo()
      //跳转到登录页
      router.push('/login')
    }
    

    return Promise.reject(e)
  })
  
  //导出
export default httpInstance

